{% extends 'admin_panel/base.html' %}

{% block title %}创建旅行记录 - 旅行记录管理系统{% endblock %}
{% block page_title %}创建旅行记录{% endblock %}

{% block content %}
<div class="row">
    <div class="col-md-8">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">填写旅行信息</h5>
            </div>
            <div class="card-body">
                <form method="post">
                    {% csrf_token %}
                    
                    {% if form.errors %}
                    <div class="alert alert-danger">
                        <strong>表单验证失败：</strong>请检查以下错误：
                        <ul>
                            {% for field, errors in form.errors.items %}
                                {% for error in errors %}
                                    <li>{{ error }}</li>
                                {% endfor %}
                            {% endfor %}
                        </ul>
                    </div>
                    {% endif %}

                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="title" class="form-label">标题 *</label>
                            <input type="text" class="form-control" id="title" name="title" 
                                   value="{{ form.title.value|default:'' }}" required>
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label for="location" class="form-label">地点</label>
                            <div class="input-group">
                                <input type="text" class="form-control" id="location" name="location" 
                                       value="{{ form.location.value|default:'' }}">
                                <button type="button" class="btn btn-outline-secondary" data-bs-toggle="modal" data-bs-target="#mapModal">
                                    <i class="bi bi-geo-alt"></i> 地图选择
                                </button>
                            </div>
                        </div>
                    </div>

                    <div class="mb-3">
                        <label for="description" class="form-label">描述</label>
                        <textarea class="form-control" id="description" name="description" 
                                  rows="4">{{ form.description.value|default:'' }}</textarea>
                    </div>

                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="start_date" class="form-label">开始日期</label>
                            <input type="date" class="form-control" id="start_date" name="start_date" 
                                   value="{{ form.start_date.value|default:'' }}">
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label for="end_date" class="form-label">结束日期</label>
                            <input type="date" class="form-control" id="end_date" name="end_date" 
                                   value="{{ form.end_date.value|default:'' }}">
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="latitude" class="form-label">纬度</label>
                            <input type="number" step="any" class="form-control" id="latitude" name="latitude" 
                                   value="{{ form.latitude.value|default:'' }}">
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label for="longitude" class="form-label">经度</label>
                            <input type="number" step="any" class="form-control" id="longitude" name="longitude" 
                                   value="{{ form.longitude.value|default:'' }}">
                        </div>
                    </div>

                    <!-- 图片上传区域 -->
                    <div class="mb-4">
                        <label class="form-label">图片上传</label>
                        <div class="card">
                            <div class="card-body">
                                <div class="d-flex justify-content-between align-items-center mb-3">
                                    <span class="text-muted">
                                        已选择 <span id="file_count">0</span> / <span id="max_files">50</span> 张图片
                                        (<span id="remaining_files">50</span> 张剩余)
                                    </span>
                                    <label for="image_upload" class="btn btn-primary btn-sm mb-0">
                                        <i class="bi bi-plus me-1"></i>选择图片
                                    </label>
                                    <input type="file" id="image_upload" accept="image/*" multiple 
                                           style="display: none;">
                                </div>
                                
                                <div id="image_preview" class="d-flex flex-wrap gap-2"></div>
                                
                    <small class="text-muted">
                        支持 JPG, PNG, GIF 格式，每张图片最大 5MB，最多 50 张
                    </small>
                </div>
            </div>
        </div>

        <div class="d-flex gap-2">
                        <button type="submit" class="btn btn-primary">
                            <i class="bi bi-check-lg me-2"></i>创建记录
                        </button>
                        <a href="{% url 'admin_panel:admin_travel_list' %}" class="btn btn-secondary">
                            <i class="bi bi-x-lg me-2"></i>取消
                        </a>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <div class="col-md-4">
        <div class="card">
            <div class="card-header">
                <h6 class="card-title mb-0">创建提示</h6>
            </div>
            <div class="card-body">
                <div class="alert alert-info">
                    <h6 class="alert-heading"><i class="bi bi-info-circle me-2"></i>填写说明</h6>
                    <ul class="mb-0 small">
                        <li>标题为必填项，建议简洁明了</li>
                        <li>地点信息可以帮助用户快速定位</li>
                        <li>经纬度用于地图显示，可选填</li>
                        <li>日期信息可以帮助整理旅行时间线</li>
                        <li>详细描述可以让其他用户了解旅行详情</li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
</div>
{% include 'admin_panel/map_selector.html' %}
{% endblock %}

{% block extra_js %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    // 日期验证
    const startDateInput = document.getElementById('start_date');
    const endDateInput = document.getElementById('end_date');
    
    if (startDateInput && endDateInput) {
        startDateInput.addEventListener('change', function() {
            if (endDateInput.value && new Date(this.value) > new Date(endDateInput.value)) {
                alert('开始日期不能晚于结束日期');
                this.value = '';
            }
        });
        
        endDateInput.addEventListener('change', function() {
            if (startDateInput.value && new Date(this.value) < new Date(startDateInput.value)) {
                alert('结束日期不能早于开始日期');
                this.value = '';
            }
        });
    }

    // 图片上传功能
    const imageUpload = document.getElementById('image_upload');
    const imagePreview = document.getElementById('image_preview');
    const selectedFiles = [];
    const maxFiles = 50;

    if (imageUpload && imagePreview) {
        // 文件选择处理
        imageUpload.addEventListener('change', function(e) {
            const files = e.target.files;
            if (!files.length) return;

            // 检查文件数量限制
            if (selectedFiles.length + files.length > maxFiles) {
                alert(`最多只能上传 ${maxFiles} 张图片`);
                this.value = '';
                return;
            }

            for (let i = 0; i < files.length; i++) {
                const file = files[i];
                
                // 验证文件类型
                if (!file.type.startsWith('image/')) {
                    alert('请选择图片文件');
                    continue;
                }

                // 验证文件大小（最大5MB）
                if (file.size > 5 * 1024 * 1024) {
                    alert('图片大小不能超过5MB');
                    continue;
                }

                selectedFiles.push(file);
                createImagePreview(file, selectedFiles.length - 1);
            }

            this.value = '';
            updateFileInputState();
        });

        // 创建图片预览
        function createImagePreview(file, index) {
            const previewUrl = URL.createObjectURL(file);
            
            const previewItem = document.createElement('div');
            previewItem.className = 'image-preview-item';
            previewItem.innerHTML = `
                <img src="${previewUrl}" alt="预览图片">
                <button type="button" class="btn btn-danger btn-sm remove-image" data-index="${index}">
                    <i class="bi bi-x"></i>
                </button>
            `;
            
            imagePreview.appendChild(previewItem);

            // 添加删除事件
            previewItem.querySelector('.remove-image').addEventListener('click', function() {
                const index = parseInt(this.dataset.index);
                removeImage(index);
            });
        }

        // 删除图片
        function removeImage(index) {
            // 释放对象URL
            const img = imagePreview.children[index].querySelector('img');
            URL.revokeObjectURL(img.src);
            
            // 从数组中移除
            selectedFiles.splice(index, 1);
            
            // 重新渲染预览
            refreshImagePreviews();
            updateFileInputState();
        }

        // 刷新所有预览
        function refreshImagePreviews() {
            imagePreview.innerHTML = '';
            selectedFiles.forEach((file, index) => {
                createImagePreview(file, index);
            });
        }

        // 更新文件输入状态
        function updateFileInputState() {
            const remaining = maxFiles - selectedFiles.length;
            document.getElementById('file_count').textContent = selectedFiles.length;
            document.getElementById('max_files').textContent = maxFiles;
            document.getElementById('remaining_files').textContent = remaining;
            
            if (remaining === 0) {
                imageUpload.disabled = true;
                imageUpload.setAttribute('title', '已达到最大上传数量');
            } else {
                imageUpload.disabled = false;
                imageUpload.removeAttribute('title');
            }
        }

        // 表单提交处理
        const form = document.querySelector('form');
        form.addEventListener('submit', function(e) {
            // 创建FormData对象
            const formData = new FormData(this);
            
            // 添加所有图片文件
            selectedFiles.forEach((file, index) => {
                formData.append('images', file);
            });

            // 使用fetch提交表单
            e.preventDefault();
            
            const submitBtn = this.querySelector('button[type="submit"]');
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="bi bi-arrow-repeat spinner"></i> 创建中...';

            fetch(this.action, {
                method: 'POST',
                body: formData,
                headers: {
                    'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value,
                }
            })
            .then(response => {
                if (response.redirected) {
                    window.location.href = response.url;
                } else if (response.ok) {
                    // 检查是否是JSON响应
                    const contentType = response.headers.get('content-type');
                    if (contentType && contentType.includes('application/json')) {
                        return response.json();
                    } else {
                        // 如果不是JSON，直接重定向
                        window.location.href = '{% url "admin_panel:admin_travel_list" %}';
                        return null;
                    }
                } else {
                    throw new Error('提交失败');
                }
            })
            .then(data => {
                if (data && data.success) {
                    window.location.href = data.redirect_url;
                } else if (!data) {
                    // 已经重定向，不需要处理
                } else {
                    throw new Error(data.error || '提交失败');
                }
            })
            .catch(error => {
                alert('提交失败: ' + error.message);
                submitBtn.disabled = false;
                submitBtn.innerHTML = '<i class="bi bi-check-lg me-2"></i>创建记录';
            });
        });

        // 不需要主图选择功能，已移除
    }
});
</script>
{% endblock %}
